# 后端 Dockerfile
# 使用阿里云镜像源
FROM registry.cn-hangzhou.aliyuncs.com/library/node:18-alpine AS builder

# 设置工作目录
WORKDIR /app

# 复制 package.json 和 package-lock.json
COPY package*.json ./

# 安装依赖
RUN npm ci --only=production && npm cache clean --force

# 复制源代码
COPY . .

# 构建应用
RUN npm run build

# 生产环境镜像
FROM registry.cn-hangzhou.aliyuncs.com/library/node:18-alpine AS production

# 创建应用用户
RUN addgroup -g 1001 -S nodejs
RUN adduser -S devops -u 1001

# 设置工作目录
WORKDIR /app

# 复制构建产物和依赖
COPY --from=builder --chown=devops:nodejs /app/dist ./dist
COPY --from=builder --chown=devops:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=devops:nodejs /app/package*.json ./

# 创建日志目录
RUN mkdir -p /app/logs && chown -R devops:nodejs /app/logs

# 切换到应用用户
USER devops

# 暴露端口
EXPOSE 8000

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8000/health || exit 1

# 启动应用
CMD ["node", "dist/index.js"]